<?php
defined('OA_LIB_PATH') || define('OA_LIB_PATH', '/opt/op/OALib');
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OA_LIB_PATH . '/util/config/Config.php';
require_once OA_LIB_PATH . '/util/db/common.php';
require_once OA_LIB_PATH . '/util/db/Base.php';
require_once OA_LIB_PATH . '/util/db/GlobalDb.php';
require_once OA_LIB_PATH . '/util/model/OpModel.php';
require_once OA_LIB_PATH . '/util/model/OpTableModel.php';
require_once OA_LIB_PATH . '/util/auth/User.php';

require_once OPEN_LIB_PATH . '/open/models/common.php';
require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaCompanyModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaAuthorityModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaCodeModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaAppConfigOrderModel.php';

require_once 'Date.php';
require_once 'Log.php';

define('OA_WEB_DB_CLUSTER_ID', 2);
define('DM_OAII_OA_DB_CLUSTER_ID', 21);
define('DM_OAII_OAWEB_DB_CLUSTER_ID', 22);
define('DM_OAII_OAPRE_DB_CLUSTER_ID', 23);
define('DM_OAII_OAS_DB_CLUSTER_ID', 24);
define('DM_OAII_OASPRE_DB_CLUSTER_ID', 25);

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_ERR);

$dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
$db = OpDbModel::getInstance($dbConfig, $logger);
$userMigrationTable = new OpTableModel($db, 'user_migration', $logger);
$developerTable = new OpTableModel($db, 'developer', $logger);
$companyTable = new OpTableModel($db, 'company', $logger);
$companyDeveloperTable = new OpTableModel($db, 'company_developer', $logger);
$appTable = new OpTableModel($db, 'app', $logger);
$appConfigTable = new OpTableModel($db, 'app_config', $logger);
$appDeveloperTable = new OpTableModel($db, 'app_developer', $logger);
$appAreaTable = new OpTableModel($db, 'app_area', $logger);
$appGroupTable = new OpTableModel($db, 'app_group', $logger);
$appServerTable = new OpTableModel($db, 'app_server', $logger);
$appLoginServerTable = new OpTableModel($db, 'app_login_server', $logger);
$appLoginServerValidTable = new OpTableModel($db, 'app_login_server_valid', $logger);
$appPayServerTable = new OpTableModel($db, 'app_pay_server', $logger);
$appPayServerValidTable = new OpTableModel($db, 'app_pay_server_valid', $logger);
$appConfigOrderTable = new OpTableModel($db, 'app_config_order', $logger);
$appSnapshotTable = new OpTableModel($db, 'app_snapshot', $logger);

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OAWEB_DB_CLUSTER_ID);
$dbOaIIOaWeb = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOaWeb) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OA_DB_CLUSTER_ID);
$dbOaIIOa = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOa) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OAPRE_DB_CLUSTER_ID);
$dbOaIIOaPre = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOaPre) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OAS_DB_CLUSTER_ID);
$dbOaIIOas = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOas) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

$dbConfig = Oa_Util_Config::getSingleDbConfig(DM_OAII_OASPRE_DB_CLUSTER_ID);
$dbOaIIOasPre = oci_connect($dbConfig['user'], $dbConfig['pass'], 
	"{$dbConfig['host']}:{$dbConfig['port']}/{$dbConfig['name']}", 'AL32UTF8');
if (!$dbOaIIOasPre) {
    $e = oci_error($st);
    $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
    exit();
}

function getUidByUserId($userId, &$message)
{
    /* @var $logger Log */
    global $logger;
    /* @var $userMigrationTable OpTableModel */
    global $userMigrationTable;
    
    $user = $userMigrationTable->getRow(array(
        'user_id' => $userId
    ));
    if (is_array($user)) {
        return $user['uid'];
    } else {
        $message = "user not exists: user_id-$userId";
        return false;
    }
}

function importCompany($companyId, &$message)
{
    /* @var $logger Log */
    global $logger;
    global $dbOaIIOa;
    global $dbOaIIOaWeb;
    /* @var $companyTable OpTableModel */
    global $companyTable;
    /* @var $companyDeveloperTable OpTableModel */
    global $companyDeveloperTable;
    
    // 从TB_SP表读取商户信息
    $sql = "SELECT SPNAME, SPADDR, EMAIL, PHONENUMBER, TELEPHONE, 
    	TO_CHAR(CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME, 
    	CREATEUSERID, TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME, 
    	COMPANY_URL, SP_CARDNUM, PRODUCT_INFO, NOTES, ZIPCODE, STATUS,
    	TO_CHAR(BEGINTIME, 'YYYY-MM-DD HH24:MI:SS') AS BEGINTIME, 
    	TO_CHAR(ENDTIME, 'YYYY-MM-DD HH24:MI:SS') AS ENDTIME 
    	FROM TB_SP WHERE SPID=:companyId";
    $st = oci_parse($dbOaIIOa, $sql);
    oci_bind_by_name($st, ':companyId', $companyId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    $company = oci_fetch_assoc($st);
    if ($company === false) {
        $message = "company not exists: company_id-$companyId";
        return false;
    }
    $companyCreator = getUidByUserId($company['CREATEUSERID'], $message);
    if ($companyCreator === false) {
        $message = "company creator not exists, creator-{$company['CREATEUSERID']}";
        return false;
    }
    
    // 插入公司表
    if (!$companyTable->insert(array(
        'id' => $companyId,
        'name' => $company['SPNAME'],
        'address' => $company['SPADDR'],
        'email' => $company['EMAIL'],
        'phone' => $company['PHONENUMBER'],
        'legal_person_phone' => $company['TELEPHONE'],
        'create_time' => $company['CREATETIME'],
        'creator' => $companyCreator,
        'tm' => $company['UPDATETIME'],
        'homepage' => $company['COMPANY_URL'],
        'legal_person_cert_no' => $company['SP_CARDNUM'],
        'legal_person_cert_type' => OaCompanyModel::CERTIFICATE_TYPE_ID_CARD,
        'intro' => $company['PRODUCT_INFO'],
        'notes' => $company['NOTES'],
        'zip_code' => $company['ZIPCODE'],
        'status' => $company['STATUS'],
        'join_status' => OaCompanyModel::JOIN_STATUS_AUDIT_OK,
        'release_status' => OaCompanyModel::RELEASE_STATUS_AUDIT_OK,
        'contract_begin_time' => $company['BEGINTIME'],
        'contract_end_time' => $company['ENDTIME'],
        'grade' => OaCompanyModel::COMPANY_GRADE_SENIOR
    ))) {
        $message = "insert into company table failed: company_id-$companyId";
        return false;
    }
    
    // 导入商户下的成员
    $sql = "SELECT ID FROM TB_USER WHERE TRUE_SPID=:companyId";
    $st = oci_parse($dbOaIIOaWeb, $sql);
    oci_bind_by_name($st, ':companyId', $companyId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    while ($row = oci_fetch_assoc($st)) {
        $uid= getUidByUserId($row['ID'], $message);
        if ($uid === false) {
            $logger->warning("company employee not exists, user-{$row['ID']}");
            continue;
        }
        if ($uid == $companyCreator) {
            $role = OaAuthorityModel::ROLE_COMPANY_ADMIN;
        } else {
            $role = OaAuthorityModel::ROLE_COMPANY_EMPLOYEE;
        }
        if (!$companyDeveloperTable->insert(array(
            'company_id' => $companyId,
            'developer_id' => $uid,
            'role' => $role
        ))) {
            $message = "insert into company developer table failed: company_id-$companyId developer_id-$uid";
            return false;
        }
    }
    
    // 同步公司信息到连调环境
    $companyModel = new OaCompanyModel($logger);
    $codeModel = new OaCodeModel($logger);
    $company = $companyModel->getCompany($companyId);
    if ($codeModel->getCompany($companyId, OaAppModel::APP_CONFIG_ENV_TEST)) {
        $updateRow = array();
        
        if (!$codeModel->modifyCompany($companyId, OaCodeModel::convertFieldNameOfCompany($company), 
            OaAppModel::APP_CONFIG_ENV_TEST)) {
            $logger->warning("sync to code failed: company-$companyId");
        }
    } else {
        if (!$codeModel->addCompany($companyId, $company['name'], $company['status'], 
            $company['notes'], array(), OaAppModel::APP_CONFIG_ENV_TEST)) {
            $logger->warning("sync to code failed: company-$companyId");
        }
    }
    $logger->info("sync to code succeed: company-$companyId");
	$params = array(
		'spId' => $companyId,
		'spName' => $company['name'],
		'spAddr' => $company['address'],
		'email' => $company['email'],
		'phoneNumber' => $company['phone'],
		'status' => $company['status'],
		'beginTime' => $company['contract_begin_time'],
		'endTime' => $company['contract_end_time'],
		'createUserId' => $company['creator'],
		'updateUserId' => $company['creator'],
		'companyUrl' => $company['homepage'],
		'spCardNum' => $company['legal_person_cert_no'],
		'productInfo' => $company['intro'],
		'notes' => $company['notes'],
		'zipCode' => $company['zip_code']
	);
	OASApi::sp($message, $params, 'add', OaAppModel::APP_CONFIG_ENV_TEST);
	OASApi::sp($message, $params, 'update', OaAppModel::APP_CONFIG_ENV_TEST);
	$logger->info("sync to oas succeed: company-$companyId");
    
    return true;
}

function deleteCompany($companyId, &$message)
{
    /* @var $companyTable OpTableModel */
    global $companyTable;
    /* @var $companyDeveloperTable OpTableModel */
    global $companyDeveloperTable;
    
    if (!$companyTable->delete(array(
        'id' => $companyId
    ))) {
        $message = "delete from company table failed: company_id-$companyId";
        return false;
    }
    
    if (!$companyDeveloperTable->delete(array(
        'company_id' => $companyId
    ))) {
        $message = "delete from company developer failed: company_id-$companyId";
        return false;
    }
    
    return true;
}
function importKey($appId, $env, &$message)
{
    global $dbOaIIOas;
    global $dbOaIIOasPre;
    /* @var $appConfigTable OpTableModel */
    global $appConfigTable;
    
    $sql = "SELECT APPPUBLICKEY, SNDAPUBLICKEY, SNDAPRIVATEKEY FROM TBRSAKEY 
    	WHERE APPID=:app_id";
    if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
        $st = oci_parse($dbOaIIOasPre, $sql);
    } else {
        $st = oci_parse($dbOaIIOas, $sql);
    }
    oci_bind_by_name($st, ':app_id', $appId);
    if (!oci_execute($st)) {
        $e = oci_error();
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    $row = oci_fetch_assoc($st);
    if ($row) {
        if (!$appConfigTable->update(array(
            'environment' => $env,
            'app_id' => $appId
        ), array(
            'app_pub_key' => $row['APPPUBLICKEY'],
            'snda_pub_key' => $row['SNDAPUBLICKEY'],
            'snda_private_key' => $row['SNDAPRIVATEKEY']
        ))) {
            $message = "update app config failed: app_id-$appId";
            return false;
        }
    }
    
    return true;
}

function importAreaGroupServer($appId, $env, &$message)
{
    /* @var $logger Log */
    global $logger;
    global $dbOaIIOaPre;
    global $dbOaIIOa;
    /* @var $appAreaTable OpTableModel */
    global $appAreaTable;
    /* @var $appGroupTable OpTableModel */
    global $appGroupTable;
    /* @var $appServerTable OpTableModel */
    global $appServerTable;
    
    $sql = "SELECT SERVICEID, AREAID, NAME, STATUS, CREATEUSER, 
    	TO_CHAR(CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME, 
    	TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME
    	FROM TB_AREA WHERE SERVICEID=:app_id";
    if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
        $st = oci_parse($dbOaIIOaPre, $sql);
    } else {
        $st = oci_parse($dbOaIIOa, $sql);
    }
    oci_bind_by_name($st, ':app_id', $appId);
    if (!oci_execute($st)) {
        $e = oci_error();
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    while ($area = oci_fetch_assoc($st)) {
        $areaCreator = getUidByUserId($area['CREATEUSER'], $message);
        if ($areaCreator === false) {
            $areaCreator = 0;
        }
        $areaId = $appAreaTable->insert(array(
            'area_code' => $area['AREAID'],
            'app_id' => $appId,
            'name' => $area['NAME'],
            'status' => $area['STATUS'],
            'creator' => $areaCreator,
            'create_time' => $area['CREATETIME'],
            'tm' => $area['UPDATETIME'],
            'environment' => $env
        ));
        if (!$areaId) {
            $message = "insert into app area table failed: app_id-$appId area_code-{$area['AREAID']}";
            return false;
        }
    
        // 导入区下的组
        $sql = "SELECT GID, GROUP_ID, GROUP_NAME, CREATEUSER, STATUS, IDC,
        	TO_CHAR(CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME, 
        	TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME
        	FROM TB_GROUP WHERE SERVICE_ID=:app_id AND AREA_ID=:area_code";
        if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
            $st1 = oci_parse($dbOaIIOaPre, $sql);
        } else {
            $st1 = oci_parse($dbOaIIOa, $sql);
        }
        oci_bind_by_name($st1, ':app_id', $area['SERVICEID']);
        oci_bind_by_name($st1, ':area_code', $area['AREAID']);
        if (!oci_execute($st1)) {
            $e = oci_error();
            $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
            return false;
        }
        while ($group = oci_fetch_assoc($st1)) {
            $groupCreator = getUidByUserId($group['CREATEUSER'], $message);
            if ($groupCreator === false) {
                $groupCreator = 0;
            }
            $groupId = $appGroupTable->insert(array(
                'group_code' => $group['GROUP_ID'],
                'name' => $group['GROUP_NAME'],
                'area_id' => $areaId,
                'creator' => $groupCreator,
                'create_time' => $group['CREATETIME'],
                'tm' => $group['UPDATETIME'],
                'status' => $group['STATUS'],
                'idc_type' => $group['IDC']
            ));
            if (!$groupId) {
                $message = "insert into app group table failed: app_id-$appId area_code-{$area['AREAID']}";
                $message .= " group_code-{$group['GROUP_ID']}";
                return false;
            }
    
            // 导入组下的服务器
            $sql = "SELECT TO_CHAR(t1.CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME,
            	t2.IP_ID AS IP_ID, t2.CLIENTIP AS CLIENTIP, t2.ALIAS AS ALIAS,
            	TO_CHAR(t2.UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME
            	FROM TB_GROUPLIST t1 JOIN TB_IPLIST t2 ON t1.IP_ID=t2.IP_ID 
            	WHERE t1.GID=:gid";
            if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
                $st2 = oci_parse($dbOaIIOaPre, $sql);
            } else {
                $st2 = oci_parse($dbOaIIOa, $sql);
            }
            oci_bind_by_name($st2, ':gid', $group['GID']);
            if (!oci_execute($st2)) {
                $e = oci_error();
                $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
                return false;
            }
            while ($server = oci_fetch_assoc($st2)) {
                if (!$appServerTable->insert(array(
                    'group_id' => $groupId,
                    'ip_id' => $server['IP_ID'],
                    'create_time' => $server['CREATETIME'],
                    'tm' => $server['UPDATETIME'],
                    'ip' => $server['CLIENTIP'],
                    'alias' => $server['ALIAS']
                ))) {
                    $message = "insert into app server table failed: app_id-$appId area_code-{$area['AREAID']}";
                    $message .= " group_code-{$group['GROUP_ID']} ip_id-{$server['IP_ID']}";
                    return false;
                }
            }
        }
    }
    
    return true;
}

function importLoginServer($appId, $env, &$message)
{
    /* @var $logger Log */
    global $logger;
    global $dbOaIIOaPre;
    global $dbOaIIOa;
    /* @var $appAreaTable OpTableModel */
    global $appAreaTable;
    /* @var $appGroupTable OpTableModel */
    global $appGroupTable;
    /* @var $appServerTable OpTableModel */
    global $appServerTable;
    /* @var $appLoginServerTable OpTableModel */
    global $appLoginServerTable;
    /* @var $appLoginServerValidTable OpTableModel */
    global $appLoginServerValidTable;
    
    $sql = "SELECT t1.LOGINID AS LOGINID, t1.AREAID AS AREAID, t1.GROUPID AS GROUPID, t1.IPID AS IPID, 
    	t1.STATUS AS STATUS, TO_CHAR(t1.CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME,
    	TO_CHAR(t1.UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME,
    	t2.IP_ID AS IP_ID, t2.CLIENTIP AS CLIENTIP, t2.ALIAS AS ALIAS, t2.HOSTID AS HOSTID
    	FROM TBLOGINSERVER t1 JOIN TB_IPLIST t2 ON t1.LOGINSERVERID=t2.IP_ID 
    	WHERE t1.SERVICEID=:app_id";
    if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
        $st = oci_parse($dbOaIIOaPre, $sql);
    } else {
        $st = oci_parse($dbOaIIOa, $sql);
    }
    oci_bind_by_name($st, ':app_id', $appId);
    if (!oci_execute($st)) {
        $e = oci_error();
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    while ($loginServerValidTo = oci_fetch_assoc($st)) {
        $loginServer = $appLoginServerTable->getRow(array(
            'environment' => $env,
            'ip_id' => $loginServerValidTo['IP_ID']
        ));
        if (is_array($loginServer)) {
            $loginServerId = $loginServer['id'];
        } else {
            $loginServerId = $appLoginServerTable->insert(array(
                'app_id' => $appId,
                'environment' => $env,
                'ip_id' => $loginServerValidTo['IP_ID'],
                'ip' => $loginServerValidTo['CLIENTIP'],
                'alias' => $loginServerValidTo['ALIAS'],
                'idc_type' => $loginServerValidTo['HOSTID'],
                'create_time' => $loginServerValidTo['CREATETIME'],
                'tm' => $loginServerValidTo['UPDATETIME']
            ));
            if (!$loginServerId) {
                $message = "insert into app login server table failed: app_id-$appId ip_id-{$loginServerValidTo['IP_ID']}";
                return false;
            }
        }
        $areaId = -1;
        if ($loginServerValidTo['AREAID'] > 0) {
            $area = $appAreaTable->getRow(array(
                'environment' => $env,
                'app_id' => $appId,
                'area_code' => $loginServerValidTo['AREAID']
            ));
            if (is_array($area)) {
                $areaId = $area['id'];
            } else {
                $logger->warning("area not exists: app_id-$appId area_code-{$loginServerValidTo['AREAID']}");
            }
        }
        $groupId = -1;
        if ($loginServerValidTo['GROUPID'] > 0) {
            $group = $appGroupTable->getRow(array(
                'area_id' => $area['id'],
                'group_code' => $loginServerValidTo['GROUPID']
            ));
            if (is_array($group)) {
                $groupId = $group['id'];
            } else {
                $logger->warning("group not exists: area_id-{$area['id']} group_code-{$loginServerValidTo['GROUPID']}");
            }
        }
        $serverId = -1;
        if ($loginServerValidTo['IPID'] > 0) {
            $sql = "SELECT app_server.* FROM app_area,app_group,app_server 
            	WHERE app_server.ip_id=" . escapeInputValue($loginServerValidTo['IPID']) . 
            	" AND app_server.group_id=app_group.id AND app_group.area_id=app_area.id 
            	AND app_area.environment=" . escapeInputValue($env);
            $server = $appServerTable->queryRow($sql);
            if (is_array($server)) {
                $serverId = $server['id'];
            } else {
                $logger->warning("server not exists: ip_id-{$loginServerValidTo['IPID']}");
            }
        }
        if (!$appLoginServerValidTable->insert(array(
            'valid_to_area' => $areaId,
            'valid_to_group' => $groupId,
            'valid_to_server' => $serverId,
            'status' => $loginServerValidTo['STATUS'],
            'login_server_id' => $loginServerId,
            'tm' => $loginServerValidTo['UPDATETIME'],
            'login_id' => $loginServerValidTo['LOGINID']
        ))) {
            $message = "insert into app login server valid table failed: valid_to_area-$areaId";
            $message .= " valid_to_group-$groupId valid_to_server-$serverId";
            $message .= " login_server_id-$loginServerId";
            return false;
        }
    }
    
    return true;
}

function importPayServer($appId, $env, &$message)
{
    /* @var $logger Log */
    global $logger;
    global $dbOaIIOaPre;
    global $dbOaIIOa;
    /* @var $appAreaTable OpTableModel */
    global $appAreaTable;
    /* @var $appGroupTable OpTableModel */
    global $appGroupTable;
    /* @var $appServerTable OpTableModel */
    global $appServerTable;
    /* @var $appPayServerTable OpTableModel */
    global $appPayServerTable;
    /* @var $appPayServerValidTable OpTableModel */
    global $appPayServerValidTable;
    
    $sql = "SELECT t1.AREAID AS AREAID, t1.GROUPID AS GROUPID, t1.IPID AS IPID, 
    	t1.STATUS AS STATUS, t1.USERIDTYPE AS USERIDTYPE, t1.SENDADDRTYPE AS SENDADDRTYPE, 
    	t1.SENDADDR AS SENDADDR, t1.NEEDCONFIRM AS NEEDCONFIRM, t1.SENDIPID AS SENDIPID, 
    	t1.CFGID AS CFGID, TO_CHAR(t1.CREATETIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATETIME,
    	TO_CHAR(t1.UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME,
    	t2.IP_ID AS IP_ID, t2.CLIENTIP AS CLIENTIP, t2.ALIAS AS ALIAS, t2.HOSTID AS HOSTID
    	FROM TB_QFTCFG t1 JOIN TB_IPLIST t2 ON t1.SENDIPID=t2.IP_ID WHERE t1.SERVICEID=:app_id";
    if ($env == OaAppModel::APP_CONFIG_ENV_TEST) {
        $st = oci_parse($dbOaIIOaPre, $sql);
    } else {
        $st = oci_parse($dbOaIIOa, $sql);
    }
    oci_bind_by_name($st, ':app_id', $appId);
    if (!oci_execute($st)) {
        $e = oci_error();
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    while ($payServerValidTo = oci_fetch_assoc($st)) {
        $payServer = $appPayServerTable->getRow(array(
            'environment' => $env,
            'ip_id' => $payServerValidTo['IP_ID']
        ));
        if (is_array($payServer)) {
            $payServerId = $payServer['id'];
        } else {
            $payServerId = $appPayServerTable->insert(array(
                'environment' => $env,
                'app_id' => $appId,
                'user_id_type' => $payServerValidTo['USERIDTYPE'],
                'type' => $payServerValidTo['SENDADDRTYPE'],
                'addr' => $payServerValidTo['SENDADDR'],
                'ip' => $payServerValidTo['CLIENTIP'],
                'alias' => $payServerValidTo['ALIAS'],
                'idc_type' => $payServerValidTo['HOSTID'],
                'need_confirm' => $payServerValidTo['NEEDCONFIRM'],
                'create_time' => $payServerValidTo['CREATETIME'],
                'tm' => $payServerValidTo['UPDATETIME'],
                'ip_id' => $payServerValidTo['SENDIPID']
            ));
            if (!$payServerId) {
                $message = "insert into app pay server table failed: app_id-$appId ip_id-{$payServerValidTo['IP_ID']}";
                return false;
            }
        }
        $areaId = -1;
        if ($payServerValidTo['AREAID'] > 0) {
            $area = $appAreaTable->getRow(array(
                'environment' => $env,
                'app_id' => $appId,
                'area_code' => $payServerValidTo['AREAID']
            ));
            if (is_array($area)) {
                $areaId = $area['id'];
            } else {
                $logger->warning("area not exists: app_id-$appId area_code-{$payServerValidTo['AREAID']}");
            }
        }
        $groupId = -1;
        if ($payServerValidTo['GROUPID'] > 0) {
            $group = $appGroupTable->getRow(array(
                'area_id' => $area['id'],
                'group_code' => $payServerValidTo['GROUPID']
            ));
            if (is_array($group)) {
                $groupId = $group['id'];
            } else {
                $logger->warning("group not exists: area_id-{$area['id']} group_code-{$payServerValidTo['GROUPID']}");
            }
        }
        $serverId = -1;
        if ($payServerValidTo['IPID'] > 0) {
            $sql = "SELECT app_server.* FROM app_area,app_group,app_server 
            	WHERE app_server.ip_id=" . escapeInputValue($payServerValidTo['IPID']) . 
            	" AND app_server.group_id=app_group.id AND app_group.area_id=app_area.id 
            	AND app_area.environment=" . escapeInputValue($env);
            $server = $appServerTable->queryRow($sql);
            if (is_array($server)) {
                $serverId = $server['id'];
            } else {
                $logger->warning("server not exists: ip_id-{$payServerValidTo['IPID']}");
            }
        }
        if (!$appPayServerValidTable->insert(array(
            'valid_to_area' => $areaId,
            'valid_to_group' => $groupId,
            'valid_to_server' => $serverId,
            'pay_server_id' => $payServerId,
            'status' => $payServerValidTo['STATUS'],
            'tm' => $payServerValidTo['UPDATETIME'],
            'qft_id' => $payServerValidTo['CFGID']
        ))) {
            $message = "insert into app pay server valid table failed: valid_to_area-$areaId";
            $message .= " valid_to_group-$groupId valid_to_server-$serverId";
            $message .= " pay_server_id-$payServerId";
            return false;
        }
    }
    
    return true;
}

function getTestAppId($appId, &$message)
{
    global $dbOaIIOaPre;
    
    if ($appId == 586) {
        return 586;
    } else if ($appId == 602) {
        return 999;
    } else if ($appId == 645) {
        return 645;
    } else if ($appId == 303) {
        return 303;
    }
    
    $sql = "SELECT SERVICEID FROM TB_SERVICE WHERE REAL_SERVICEID=:app_id";
    $st = oci_parse($dbOaIIOaPre, $sql);
    oci_bind_by_name($st, ':app_id', $appId);
    if (!oci_execute($st)) {
        $e = oci_error();
        $message = "[{$e['code']}] {$e['message']}: {$e['sqltext']}";
        return false;
    }
    $app = oci_fetch_assoc($st);
    if ($app === false) {
        $message = "test app not exists: app_id-$appId";
        return false;
    }
    
    return $app['SERVICEID'];
}

function importServiceConfig($appId, $env, &$message)
{
    /* @var $logger Log */
    global $logger;
    /* @var $appTable OpTableModel */
    global $appTable;
    /* @var $appConfigTable OpTableModel */
    global $appConfigTable;
    
    $app = $appTable->getRow(array(
        'id' => $appId
    ));
    if (!is_array($app)) {
        $message = "app not exist: app_id-$appId";
        return false;
    }
    $row = array(
        'service_login_status' => OaAppModel::APP_SERVICE_STATUS_OPENED,
        'service_pay_status' => OaAppModel::APP_SERVICE_STATUS_OPENED,
        'service_billing_status' => OaAppModel::APP_SERVICE_STATUS_OPENED
    );
    if ($app['type'] == OaAppModel::APP_TYPE_CLIENT) {
        $row['service_igw_status'] = OaAppModel::APP_SERVICE_STATUS_OPENED;
    } else {
        $row['service_ibw_status'] = OaAppModel::APP_SERVICE_STATUS_OPENED;
    }
    if (!$appConfigTable->update(array(
        'environment' => $env,
        'app_id' => $appId
    ), $row)) {
        $message = "update failed: app_id-$appId";
        return false;
    }
    
    return true;
}
